<template>
	<div class="wrapper">
		<!-- header部分 -->
		<header>
			<i class="fa fa-angle-left" @click="back"></i>
			<p>注册</p>
		</header>
		<!-- 注册类型选择 -->
		<div class="register-type">
			<button @click="toggleRType('user')" :class="{ active: RType === 'user' }">用户注册</button>
			<button @click="toggleRType('business')" :class="{ active: RType === 'business' }">商家注册</button>
		</div>
		<!-- 表单部分 -->
		<ul class="form-box" v-if="RType === 'user'">
					<li>
						<div class="title">
							手机号码：
						</div>
						<div class="content">
							<input type="text" @blur="checkUserId" v-model="user.userId" placeholder="手机号码" :class="{ 'input-error': errors.userId }">
							<span v-if="errors.userId" class="error-message">{{ errors.userId }}</span>
						</div>
					</li>
					<li>
						<div class="title">
							密码：
						</div>
						<div class="content">
							<input type="password" v-model="user.password" placeholder="密码" :class="{ 'input-error': errors.password }">
							<span v-if="errors.password" class="error-message">{{ errors.password }}</span>
						</div>
					</li>
					<li>
						<div class="title">
							确认密码：
						</div>
						<div class="content">
							<input type="password" v-model="confirmPassword" placeholder="确认密码" :class="{ 'input-error': errors.confirmPassword }">
							<span v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</span>
						</div>
					</li>
					<li>
						<div class="title">
							用户名称：
						</div>
						<div class="content">
							<input type="text" v-model="user.userName" placeholder="用户名称" :class="{ 'input-error': errors.userName }">
							<span v-if="errors.userName" class="error-message">{{ errors.userName }}</span>
						</div>
					</li>
					<li>
						<div class="title">
							性别：
						</div>
						<div class="content" style="font-size: 3vw;">
							<input type="radio" v-model="user.userSex" value="1" style="width:6vw;height: 3.2vw;">男
							<input type="radio" v-model="user.userSex" value="0" style="width:6vw;height: 3.2vw;">女
						</div>
					</li>
				</ul>
		<ul class="form-box" v-if="RType === 'business'">
		  <li>
		    <div class="title">
		      商家ID：
		    </div>
		    <div class="content">
		      <input type="text" @blur="checkBusinessId" v-model="business.businessId" placeholder="商家ID" :class="{ 'input-error': errors.businessId }">
		      <span v-if="errors.businessId" class="error-message">{{ errors.businessId }}</span>
		    </div>
		  </li>
		  <li>
		    <div class="title">
		      密码：
		    </div>
		    <div class="content">
		      <input type="password" v-model="business.password" placeholder="密码" :class="{ 'input-error': errors.password }">
		      <span v-if="errors.password" class="error-message">{{ errors.password }}</span>
		    </div>
		  </li>
		  <li>
		    <div class="title">
		      确认密码：
		    </div>
		    <div class="content">
		      <input type="password" v-model="confirmPassword" placeholder="确认密码" :class="{ 'input-error': errors.confirmPassword }">
		      <span v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</span>
		    </div>
		  </li>
		  <li>
		    <div class="title">
		      商家名称：
		    </div>
		    <div class="content">
		      <!-- 注意：商家注册应该使用商家名称而不是用户名称 -->
		      <input type="text" v-model="business.businessName" placeholder="商家名称" :class="{ 'input-error': errors.businessName }">
		      <!-- 注意：应该显示商家名称的错误消息 -->
		      <span v-if="errors.businessName" class="error-message">{{ errors.businessName }}</span>
		    </div>
		  </li>
		</ul>
		<div class="button-register">
			<button @click="register" :disabled="isSubmitting">{{ RType === 'user' ? '用户注册' : '商家注册' }}</button>
		</div>
		<!-- 底部菜单部分 -->
		<Footer></Footer>
	</div>
</template>
<script>
import Footer from '../components/Footer.vue';

export default {
  name: 'Register',
  data() {
    return {
      RType: 'user', // 默认为用户注册
      user: {
        userId: '',
        password: '',
        userName: '',
        userSex: 1
      },
      business: {
        businessId: '',
        password: '',
        businessName: ''
      },
      confirmPassword: '',
      phonePattern: /^1[3-9]\d{9}$/,  // 正确的中国电话号码格式正则表达式
      passwordPattern: /^\d{6,}$/,  // 密码至少为六位数字
      errors: {},  // 存储错误信息
      isSubmitting: false  // 防止重复提交
    }
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    toggleRType(type) {
      this.RType = type;
    },
    checkUserId() {
      this.errors.userId = '';
      if (!this.phonePattern.test(this.user.userId)) {
        this.errors.userId = '手机号码格式不正确！';
        return;
      }
	  let url =`UserController/getUserById/${this.user.userId}`;
      this.$axios.get(url)
        .then(response => {
          if (response.data.result == 1) {
            this.user.userId = '';
            this.errors.userId = '此手机号码已存在！';
          }
        }).catch(error => {
          console.error(error);
        });
    },
    checkBusinessId() {
      this.errors.businessId = '';
      if (!this.business.businessId) {
        this.errors.businessId = '商家ID不能为空！';
        return;
      }
	  let url =`BusinessAdminController/getById/${this.business.businessId}`;
      this.$axios.get(url)
        .then(response => {
          if (response.data == 1) {
            this.business.businessId = '';
            this.errors.businessId = '此商家ID已存在！';
          }
        }).catch(error => {
          console.error(error);
        });
    },
    register() {
      this.errors = {};  // 清空错误信息
      if (this.RType === 'user') {
        this.validateUser();
      } else {
        this.validateBusiness();
      }

      if (Object.keys(this.errors).length > 0) return;  // 如果有错误，停止提交

      this.isSubmitting = true;
	  let uurl =`UserController/saveUser/${this.user.userId}/${this.user.password}/${this.user.userName}/${this.user.userSex}`;
      let apiEndpoint = this.RType === 'user' ? uurl : `BusinessAdminController/saveBusiness/${this.business.businessId}/${this.business.password}/${this.business.businessName}`;
      
      this.$axios.post(apiEndpoint)
		.then(response => {
          if (response.data.result > 0) {
            alert('注册成功！');
            this.$router.push('/login');
          } else {
            alert('注册失败！');
          }
        })
        .catch(error => {
          console.error(error);
        })
        .finally(() => {
          this.isSubmitting = false;
        });
    },
    validateUser() {
      if (!this.user.userId) {
        this.errors.userId = '手机号码不能为空！';
        return;
      }
      if (!this.passwordPattern.test(this.user.password)) {
        this.errors.password = '密码至少为六位数字！';
        return;
      }
      if (this.user.password !== this.confirmPassword) {
        this.errors.confirmPassword = '两次输入的密码不一致！';
        return;
      }
      if (!this.user.userName) {
        this.errors.userName = '用户名不能为空！';
      }
    },
    validateBusiness() {
      if (!this.business.businessId) {
        this.errors.businessId = '商家ID不能为空！';
        return;
      } 
	  if (this.business.businessId.length !== 5) {
	    this.errors.businessId = '商家ID只能是5位！';
	    return;
	  }
      if (!this.passwordPattern.test(this.business.password)) {
        this.errors.password = '密码至少为六位数字！';
        return;
      }
      if (this.business.password !== this.confirmPassword) {
        this.errors.confirmPassword = '两次输入的密码不一致！';
        return;
      }
      if (!this.business.businessName) {
        this.errors.businessName = '商家名称不能为空！';
      }
    }
  },
  components: {
    Footer
  }
}
</script>

<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		height: 100%;
	}

	/****************** header部分 ******************/
	.wrapper header {
		width: 100%;
		height: 12vw;
		background-color: #01B0F2;
		font-size: 4.8vw;
		color: #fff;

		z-index: 10;

		display: flex;
		justify-content: flex-start;
		align-items: center;

		position: fixed;
		left: 0;
		top: 0;
	}

	.wrapper header i {
		margin: 0vw 0vw 0vw 3vw;
		font-size: 6vw;
		user-select: none;
		cursor: pointer;
	}

	.wrapper header p {
		margin: 0vw 0vw 0vw 32vw;
	}
	/****************** 注册类型选择 ******************/
	.register-type {
		width: 100%;
		box-sizing: border-box;
		padding: 4vw 3vw;
		display: flex;
		justify-content: space-around;

		position: fixed;   /* 固定定位 */
		bottom: 0;         /* 贴底部 */
		left: 0;           /* 左对齐 */
		background-color: #fff; /* 可选：防止背景透明 */
		z-index: 1000;     /* 保证浮在前面 */
	}
	
	.register-type button {
		width: 45%;
		height: 10vw;
		font-size: 3.8vw;
		font-weight: 700;
		color: #fff;
		background-color: #DDD;
		border-radius: 50%;
		border: none;
		outline: none;
	}
	
	.register-type button.active {
		background-color: #01B0F2;
	}
	
	.register-type button:hover {
		background-color: #666;/******/
	}
	/****************** 表单部分 ******************/
	.wrapper .form-box {
		width: 100%;
		margin-top: 12vw;
	}

	.wrapper .form-box li {
		box-sizing: border-box;
		padding: 4vw 3vw 0 3vw;
		display: flex;
		align-items: center;
	}

	.wrapper .form-box li .title {
		flex: 0 0 18vw;
		font-size: 3vw;
		font-weight: 700;
		color: #666;
	}

	.wrapper .form-box li .content {
		flex: 1;
	}

	.wrapper .form-box li .content input {
		border: none;
		outline: none;
		width: 100%;
		height: 4vw;
		font-size: 3vw;
	}

	.wrapper .form-box li .content .input-error {
		border: 1px solid #f00;
	}

	.wrapper .form-box li .content .error-message {
		color: #f00;
		font-size: 2vw;
	}

	.wrapper .button-register {
		width: 100%;
		box-sizing: border-box;
		padding: 4vw 3vw 0 3vw;
	}
	.wrapper .button-register button {
		width: 100%;
		height: 10vw;
		font-size: 3.8vw;
		font-weight: 700;
		color: #fff;
		background-color: #38CA73;
		border-radius: 4px;
		border: none;
		outline: none;
		cursor: pointer;
	}

	.wrapper .button-login button:disabled {
		background-color: #b0b0b0;
		cursor: not-allowed;
	}
</style>